﻿import { Storage } from "@plasmohq/storage"

// 创建存储实例
const storage = new Storage({
  area: "local"
})

// 存储键名常量
export const STORAGE_KEYS = {
  // 截屏相关
  SCREENSHOTS: "screenshots",
  LAST_SCREENSHOT: "lastScreenshot",
  
  // 定时器相关
  TIMERS: "timers",
  TIMER_SETTINGS: "timerSettings",
  
  // 编辑器相关
  EDITOR_CONTENT: "editorContent",
  EDITOR_HISTORY: "editorHistory",
  
  // 录屏相关
  RECORDINGS: "recordings",
  RECORDING_SETTINGS: "recordingSettings",
  
  // 用户设置
  USER_PREFERENCES: "userPreferences",
  ACTIVE_TAB: "activeTab"
} as const

// 通用存储操作
export class StorageManager {
  // 获取数据
  static async get<T>(key: string, defaultValue?: T): Promise<T | null> {
    try {
      const value = await storage.get(key)
      return value !== undefined ? value : (defaultValue || null)
    } catch (error) {
      console.error(`获取存储数据失败 (${key}):`, error)
      return defaultValue || null
    }
  }

  // 设置数据
  static async set<T>(key: string, value: T): Promise<boolean> {
    try {
      await storage.set(key, value)
      return true
    } catch (error) {
      console.error(`设置存储数据失败 (${key}):`, error)
      return false
    }
  }

  // 删除数据
  static async remove(key: string): Promise<boolean> {
    try {
      await storage.remove(key)
      return true
    } catch (error) {
      console.error(`删除存储数据失败 (${key}):`, error)
      return false
    }
  }

  // 清空所有数据
  static async clear(): Promise<boolean> {
    try {
      await storage.clear()
      return true
    } catch (error) {
      console.error("清空存储数据失败:", error)
      return false
    }
  }

  // 获取所有键
  static async keys(): Promise<string[]> {
    try {
      return await storage.keys()
    } catch (error) {
      console.error("获取存储键失败:", error)
      return []
    }
  }

  // 检查键是否存在
  static async has(key: string): Promise<boolean> {
    try {
      const value = await storage.get(key)
      return value !== undefined
    } catch (error) {
      console.error(`检查存储键失败 (${key}):`, error)
      return false
    }
  }
}

// 截屏存储管理
export class ScreenshotStorage {
  static async saveScreenshot(screenshot: {
    id: string
    dataUrl: string
    timestamp: number
    name?: string
  }): Promise<boolean> {
    const screenshots = await this.getScreenshots()
    screenshots.unshift(screenshot)
    
    // 限制最多保存50张截屏
    if (screenshots.length > 50) {
      screenshots.splice(50)
    }
    
    return await StorageManager.set(STORAGE_KEYS.SCREENSHOTS, screenshots)
  }

  static async getScreenshots(): Promise<Array<{
    id: string
    dataUrl: string
    timestamp: number
    name?: string
  }>> {
    return await StorageManager.get(STORAGE_KEYS.SCREENSHOTS, [])
  }

  static async deleteScreenshot(id: string): Promise<boolean> {
    const screenshots = await this.getScreenshots()
    const filtered = screenshots.filter(s => s.id !== id)
    return await StorageManager.set(STORAGE_KEYS.SCREENSHOTS, filtered)
  }

  static async clearScreenshots(): Promise<boolean> {
    return await StorageManager.set(STORAGE_KEYS.SCREENSHOTS, [])
  }

  static async saveLastScreenshot(screenshot: {
    dataUrl: string
    timestamp: number
  }): Promise<boolean> {
    return await StorageManager.set(STORAGE_KEYS.LAST_SCREENSHOT, screenshot)
  }

  static async getLastScreenshot(): Promise<{
    dataUrl: string
    timestamp: number
  } | null> {
    return await StorageManager.get(STORAGE_KEYS.LAST_SCREENSHOT, null)
  }
}

// 定时器存储管理
export class TimerStorage {
  static async saveTimers(timers: Array<{
    id: string
    name: string
    duration: number
    remaining: number
    isRunning: boolean
    isCompleted: boolean
    createdAt: string
  }>): Promise<boolean> {
    return await StorageManager.set(STORAGE_KEYS.TIMERS, timers)
  }

  static async getTimers(): Promise<Array<{
    id: string
    name: string
    duration: number
    remaining: number
    isRunning: boolean
    isCompleted: boolean
    createdAt: string
  }>> {
    return await StorageManager.get(STORAGE_KEYS.TIMERS, [])
  }

  static async saveTimerSettings(settings: {
    defaultMinutes: number
    maxTimers: number
    notificationsEnabled: boolean
  }): Promise<boolean> {
    return await StorageManager.set(STORAGE_KEYS.TIMER_SETTINGS, settings)
  }

  static async getTimerSettings(): Promise<{
    defaultMinutes: number
    maxTimers: number
    notificationsEnabled: boolean
  }> {
    return await StorageManager.get(STORAGE_KEYS.TIMER_SETTINGS, {
      defaultMinutes: 5,
      maxTimers: 10,
      notificationsEnabled: true
    })
  }
}

// 编辑器存储管理
export class EditorStorage {
  static async saveContent(content: string): Promise<boolean> {
    return await StorageManager.set(STORAGE_KEYS.EDITOR_CONTENT, content)
  }

  static async getContent(): Promise<string> {
    return await StorageManager.get(STORAGE_KEYS.EDITOR_CONTENT, "")
  }

  static async saveToHistory(content: string): Promise<boolean> {
    const history = await this.getHistory()
    const historyItem = {
      id: Date.now().toString(),
      content,
      timestamp: Date.now()
    }
    
    history.unshift(historyItem)
    
    // 限制历史记录最多保存20条
    if (history.length > 20) {
      history.splice(20)
    }
    
    return await StorageManager.set(STORAGE_KEYS.EDITOR_HISTORY, history)
  }

  static async getHistory(): Promise<Array<{
    id: string
    content: string
    timestamp: number
  }>> {
    return await StorageManager.get(STORAGE_KEYS.EDITOR_HISTORY, [])
  }

  static async clearHistory(): Promise<boolean> {
    return await StorageManager.set(STORAGE_KEYS.EDITOR_HISTORY, [])
  }
}

// 录屏存储管理
export class RecordingStorage {
  static async saveRecording(recording: {
    id: string
    name: string
    dataUrl: string
    timestamp: number
    duration: number
  }): Promise<boolean> {
    const recordings = await this.getRecordings()
    recordings.unshift(recording)
    
    // 限制最多保存20个录屏
    if (recordings.length > 20) {
      recordings.splice(20)
    }
    
    return await StorageManager.set(STORAGE_KEYS.RECORDINGS, recordings)
  }

  static async saveRecordings(recordings: Array<{
    id: string
    name: string
    dataUrl: string
    timestamp: number
    duration: number
  }>): Promise<boolean> {
    return await StorageManager.set(STORAGE_KEYS.RECORDINGS, recordings)
  }

  static async getRecordings(): Promise<Array<{
    id: string
    name: string
    dataUrl: string
    timestamp: number
    duration: number
  }>> {
    return await StorageManager.get(STORAGE_KEYS.RECORDINGS, [])
  }

  static async deleteRecording(id: string): Promise<boolean> {
    const recordings = await this.getRecordings()
    const filtered = recordings.filter(r => r.id !== id)
    return await StorageManager.set(STORAGE_KEYS.RECORDINGS, filtered)
  }

  static async clearRecordings(): Promise<boolean> {
    return await StorageManager.set(STORAGE_KEYS.RECORDINGS, [])
  }

  static async saveRecordingSettings(settings: {
    quality: string
    format: string
    maxDuration: number
  }): Promise<boolean> {
    return await StorageManager.set(STORAGE_KEYS.RECORDING_SETTINGS, settings)
  }

  static async getRecordingSettings(): Promise<{
    quality: string
    format: string
    maxDuration: number
  }> {
    return await StorageManager.get(STORAGE_KEYS.RECORDING_SETTINGS, {
      quality: "high",
      format: "webm",
      maxDuration: 300
    })
  }
}

// 用户偏好设置存储管理
export class UserPreferencesStorage {
  static async savePreferences(preferences: {
    activeTab: string
    theme: string
    language: string
    autoSave: boolean
    notifications: boolean
  }): Promise<boolean> {
    return await StorageManager.set(STORAGE_KEYS.USER_PREFERENCES, preferences)
  }

  static async getPreferences(): Promise<{
    activeTab: string
    theme: string
    language: string
    autoSave: boolean
    notifications: boolean
  }> {
    return await StorageManager.get(STORAGE_KEYS.USER_PREFERENCES, {
      activeTab: "screenshot",
      theme: "light",
      language: "zh-CN",
      autoSave: true,
      notifications: true
    })
  }

  static async saveActiveTab(tab: string): Promise<boolean> {
    return await StorageManager.set(STORAGE_KEYS.ACTIVE_TAB, tab)
  }

  static async getActiveTab(): Promise<string> {
    return await StorageManager.get(STORAGE_KEYS.ACTIVE_TAB, "screenshot")
  }
}

// 导出存储实例供其他模块使用
export { storage }
